package com.idconfirmsystem.fragment;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.util.EncodingUtils;

import net.tsz.afinal.FinalDb;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.idconfirmsystem.R;
import com.idconfirmsystem.activity.TaskDetailActivity;
import com.idconfirmsystem.adapter.TaskAdapter;
import com.idconfirmsystem.app.AppConfig;
import com.idconfirmsystem.lib.NetWorkUtil;
import com.idconfirmsystem.model.Task;
import com.idconfirmsystem.model.UserBean;
import com.idconfirmsystem.parse.TaskParse;
import com.idconfirmsystem.remote.ConfirmApi;
import com.idconfirmsystem.remote.TaskApi;
import com.idconfirmsystem.util.FileUtils;
import com.koushikdutta.async.future.FutureCallback;

@SuppressLint("InlinedApi")
public class PMTaskFragment extends Fragment implements
		android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener {

	List<Task> tdTasks = new ArrayList<Task>();// 今日任务
	TaskAdapter adapter;
	LinearLayout header;

	ListView tasklistView;
	// TextView taskTypeName;
	private CountDownTimer timer;
	ProgressBar progressbar;
	// TextView title;
	SwipeRefreshLayout swipe;
	FinalDb db;
	TaskParse xmlParse;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_task, container, false);
		queryTaskList(UserBean.getInstance().getUserName(), "C", UserBean
				.getInstance().getType(), FileUtils.dataUtil());
		initView(view);
		return view;
	}

	public void setTaskTypeName(String text) {
		// if (taskTypeName != null)
		// taskTypeName.setText(text);
	}

	public void refresh() {
	}

	private void initView(View view) {
		db = FinalDb.create(getActivity(), false);
		// taskTypeName = (TextView) view.findViewById(R.id.tv_task_type_name);
		if (AppConfig.curMenu != null) {
			// taskTypeName.setText(AppConfig.curMenu.getMenuName());
		}
		progressbar = (ProgressBar) view.findViewById(R.id.progressbar);
		tasklistView = (ListView) view.findViewById(R.id.tasklistView);

		tasklistView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						TaskDetailActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("taskid", xmlParse.getListDates().get(arg2)
						.get("id").toString());
				intent.putExtras(bundle);
				// toast(arg2 + "");
				startActivity(intent);
			}
		});
		header = (LinearLayout) view.findViewById(R.id.taskhead);
		if (header != null) {
			// ((TextView)
			// header.findViewById(R.id.tv_taskcode)).setText("任务编号");
			((TextView) header.findViewById(R.id.tv_taskcode)).setText("晚接任务单");
			((TextView) header.findViewById(R.id.tv_driver)).setText("驾驶员");
			((TextView) header.findViewById(R.id.tv_chargor)).setText("业务员");
			((TextView) header.findViewById(R.id.tv_sendoutTime))
					.setText("出发时间");
		}

		swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
		swipe.setOnRefreshListener(this);
		// 顶部刷新的样式
		swipe.setColorSchemeResources(android.R.color.holo_red_light,
				android.R.color.holo_green_light,
				android.R.color.holo_blue_bright,
				android.R.color.holo_orange_light);
		timer = new CountDownTimer(9 * 100, 100) {

			@Override
			public void onTick(long millisUntilFinished) {

				long a = millisUntilFinished / 100;
				if (a == 1) {
					// xmlParse = new TaskParse();
					if(xmlParse==null){
						progressbar.setVisibility(View.GONE);
						return;
					}
					if (xmlParse.getListLength() == 1
							&& xmlParse.getListDates().get(0).get("aae314")
									.equals("0")) {
						Task obj = new Task();
						Map<String, Object> map = xmlParse.getListDates()
								.get(0);
						obj.setId(map.get("id").toString());
						obj.setEscort_number1(xmlParse.getListDates().get(0)
								.get("aae317").toString());
						obj.setEscort_name1(map.get("escort_name1").toString());
						obj.setPilot_name(map.get("pilot_name").toString());
						obj.setPilot_number("");
						obj.setDeparture_time(new Date());
						tdTasks.add(obj);
					} else {
						for (int i = 0; i < xmlParse.getListLength(); i++) {
							Map<String, Object> map = xmlParse.getListDates()
									.get(i);
							// Log.e("soap33", "" + xmlParse.getListLength());
							Task obj = new Task();
							obj.setId(map.get("id").toString());
							obj.setEscort_number1("101");
							obj.setEscort_name1(map.get("escort_name1")
									.toString());
							obj.setPilot_name(map.get("pilot_name").toString());
							obj.setPilot_number("103");
							obj.setDeparture_time(new Date());
							tdTasks.add(obj);
						}
					}

					adapter = new TaskAdapter(getActivity(), tasklistView);
					progressbar.setVisibility(View.GONE);
					tasklistView.setAdapter(adapter);
					adapter.resetData(tdTasks);
				} else {
					progressbar.setVisibility(View.GONE);
				}
			}

			@Override
			public void onFinish() {

			}
		};
		// sections = db.findAllByWhere(Task.class, "1=1", "id");
		if (NetWorkUtil.networkCanUse(getActivity())) {
			timer.start();
		} else {
			// progressbar.setIndeterminateDrawable(getResources().getDrawable(R.drawable.net_error_loading));
			// if (sections != null || sections.size() != 0) {
			// adapter = new HomeAdapter(getActivity(), listView);
			// listView.setAdapter(adapter);
			// adapter.resetData(sections);
			// }
		}
	}

	/**
	 * 根据要求获取不同的任务列表（A早送 B晚接 C中调）
	 * 
	 * @param userCode
	 *            当前用户的ID
	 * @param taskType
	 *            任务类型：A早送 B晚接 C中调
	 * @param userType
	 *            用户类型：SY守押 KY客户
	 * @return void
	 */
	public void queryTaskList(final String userCode, final String taskType,
			final String userType, final String depDate) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					TaskApi ta = new TaskApi();
					String result = ta
							.getTaskSoap(userCode, taskType, userType,depDate);
					Log.e("getTaskSoap", result);
					FileUtils.writeByXml(getActivity(), result,
							FileUtils.dataUtil() + taskType + ".xml");
					xmlParse = new TaskParse(result);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void getData(String jsonurl) {
		tdTasks = new ArrayList<Task>();
		ConfirmApi.getTask(1, getDataFutureCallback);
		// test
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub

	}

	private FutureCallback getDataFutureCallback = new FutureCallback<JsonObject>() {

		@Override
		public void onCompleted(Exception e, JsonObject result) {
			// TODO Auto-generated method stub

		}
	};

	private void toast(String text) {
		Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 将Assets中的测试数据读取出来后存入SD卡中的指定位置。（当前用户存储测试数据）
	 * 
	 * @author 吴晓明
	 * @throw
	 * @return void
	 */
	public void getAssetsToSD() {

		// 存储测试数据
		try {
			String fileNameString = "20150822A.xml";
			InputStream in;
			in = getResources().getAssets().open(fileNameString);
			// 获取文件的字节数
			int lenght = in.available();
			// 创建byte数组
			byte[] buffer = new byte[lenght];
			// 将文件中的数据读到byte数组中
			in.read(buffer);
			String taskResult = EncodingUtils.getString(buffer, "utf-8");
			FileUtils.writeByXml(getActivity(), taskResult, fileNameString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
